package com.hn.sanya.demo.wx.util;

import com.hn.sanya.demo.wx.vo.message.Artics.Articles;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述: Xml和Map 互转工具类
 * @param:
 * @return:
 * @auther: lxh
 * @date: 2019/1/25
 */
public class XmlToMapUtil {

    /**
     * 功能描述: XML转Map
     * @param:
     * @return:
     * @auther: lxh
     * @date: 2019/1/25
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        try(InputStream ins=request.getInputStream()){
            Document doc=reader.read(ins);
            //根据文档对象获取根节点
            Element root = doc.getRootElement();

            //获取根节点的所有子节点并遍历放到Map
            List<Element> list = root.elements();

            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
            return map;
        }
    }
    /**
     * 功能描述: Map转XML
     * @param:
     * @return:
     * @auther: lxh
     * @date: 2019/1/25
     */
    public static String MapToXml(Object object){
        XStream xStream=new XStream();
        xStream.alias("xml",object.getClass());
        xStream.alias("item", Articles.class);
        return xStream.toXML(object);

    }



}
